package com.xhl.core.social.qq;

import com.xhl.core.social.qq.connet.QQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.security.AuthenticationNameUserIdSource;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.sql.DataSource;

/**
 * 社交配置器
 * @author xuhongliang
 * @date 2019/4/30
 */
@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {
    //数据源
    @Autowired
    private DataSource dataSource;

    /**
     *
     * @author xuhongliang
     * @date 2019/4/30
     * @param connectionFactoryLocator 如 {@link QQConnectionFactory}
     * @return org.springframework.social.connect.UsersConnectionRepository
     */
    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        /**
         * @date 2019/4/30
         * @param dataSource 数据源，脚本在 JdbcUsersConnectionRepository 的源码路径里找
         * @param connectionFactoryLocator 对应的 Factory
         * @param textEncryptors 把插入数据库的数据进行加密解密，这里选了一个不加密的
         * @return org.springframework.social.connect.UsersConnectionRepository
         */
        return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        //如果你不想你加了前缀
//        JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
//        repository.setTablePrefix("imooc_");
//        return repository
    }

    @Bean
    public SpringSocialConfigurer xhlSocialSecurityConfig() {
        return new SpringSocialConfigurer();
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new AuthenticationNameUserIdSource();
    }

    @Bean
    public ConnectController connectController(
            ConnectionFactoryLocator connectionFactoryLocator,
            ConnectionRepository connectionRepository) {
        return new ConnectController(connectionFactoryLocator, connectionRepository);
    }
}
